package service

import (
	"encoding/json"
	"io/ioutil"
	"net/http"

	"crossrun.top/control"
	"crossrun.top/model"
)

func AddCatalog(w http.ResponseWriter, r *http.Request) {
	var res model.ResPonse
	b, _ := ioutil.ReadAll(r.Body) //把  body 内容读入 b
	var f interface{}
	e := json.Unmarshal(b, &f)
	if e != nil {
		res.ResCode = "0"
		res.ResMessage = e.Error()
		data, _ := json.Marshal(res)
		w.Write(data)
		return
	}
	m := f.(map[string]interface{})

	name, ok := m["name"].(string)
	if ok {
		cata, err := control.AddCatalog(name, 1)
		if err != nil {
			res.ResCode = "0"
		} else {
			res.ResCode = "1"
			res.Res = cata
		}
	} else {
		res.ResCode = "0"
		res.ResMessage = "name miss"
	}

	data, _ := json.Marshal(res)
	w.Write(data)
}

func ListCatalog(w http.ResponseWriter, r *http.Request) {
	var res model.ResPonse
	catas, err := control.ListCataLog()
	if len(catas) < 1 || err != nil {
		res.ResCode = "0"
	} else {
		res.ResCode = "1"
		res.Res = catas
	}
	data, _ := json.Marshal(res)
	w.Write(data)
}
